package com.lyl.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author lylbell
 * @date 2021-06-30 15:03
 */
@Slf4j
public class OAuth2FeignConfig implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        //从请求里边获取token
       ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
       if (servletRequestAttributes != null) {
           String token = servletRequestAttributes.getRequest().getHeader("Authorization");
           requestTemplate.header(HttpHeaders.AUTHORIZATION,token);
       }else {
           log.info("无法获取token，因为没有上下文环境");
       }

    }
}
